import { calcTime, proxy, getscene, reqHeader, getparamstr, limitLength, isAuthorization, followAction, maiDian } from '../../utils/util.js';
import async from '../../libs/async.js';
import LoginStore from '../login/store.js';
const app = getApp();

let getDefault = function (){
  return {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0))',
      hasFilter: true,
      color: '#FFFFFF',
      btnStyle: 'white', //black, white
    },
    navBarHeight: app.globalData.height,
    userInfo: {},
    vIcon: false,
    gender: '',
    self: false,
    worksParams: {},
    worksUrl: '',
    totalWorksUrl: '',
    articleUrl: '',
    articleParams: {},
    totalArticleUrl: '',
    communityUrl: '',
    communityParams: {},
    totalCommunityUrl: '',
    popParams: {},
    isPopShow: false,
    popStyle: {
      cls: 'hChange'
    },
    sharePop: false,
    canvasHeight: 0,
    canvasHidden: true,
    curWorksType:'profileList',
    isChangeAccount:false,
    loginTypeStr: LoginStore.userInfo.loginType || "",
    userReviewState:null
  }
}

Page({
  data: getDefault(),
  sharePopShow: function () {
    this.setData({
      sharePop: true
    });
  },
  closeSharePop: function (e) {
    this.setData({
      sharePop: false
    });
    if (e.detail.makePoster) {
      this.makePoster();
    }
  },
  makePoster: function () {
    wx.showLoading({
      title: '生成中...',
      mask: true
    });

    let me = this;

    getscene(me.data.userInfo.id, (scene) => {
      let userInfo = this.data.userInfo;
      let cover_obj = {
        url: userInfo.coverUrl.p3
      }
      let avatar_obj = {
        url: userInfo.avatar.a1
      }
      let erweima_obj = {
        url: `https://node.500px.me/weChat/queryCodeImg?page=pages/userInfo/userInfo&scene=${scene}`
      }
      let dataImgs = [cover_obj, avatar_obj, erweima_obj];
      let gender_obj = {};
      if (me.data.gender) {
        gender_obj = {
          url: me.data.gender
        }
        dataImgs.push(gender_obj);
      }
      
      async.forEach(dataImgs, (item, callback) => {
        wx.getImageInfo({
          src: item.url,
          success: function (res) {
            item.res = res;
            callback();
          },
          fail: function (e) {
            console.log(e)
          }
        });
      }, function () {
        let canvasWidth = app.globalData.screenWidth;
        let coverBoxHeight = 334 / 375 * canvasWidth;
        let canvasHeight = coverBoxHeight+154;

        me.setData({
          canvasHidden: false,
          canvasHeight: canvasHeight
        }, () => {
          var context = wx.createCanvasContext('myCanvas');

          context.fillStyle = "#fff";
          context.fillRect(0, 0, canvasWidth + 10, canvasHeight+10);

          let coverImgHeight = coverBoxHeight;
          let coverImgWidth = cover_obj.res.width / cover_obj.res.height * coverImgHeight;
          let coverLeft = (coverImgWidth - canvasWidth) / 2;
          let coverTop = 0;
          if (coverImgWidth < canvasWidth) {
            coverImgWidth = canvasWidth;
            coverImgHeight = cover_obj.res.height / cover_obj.res.width * coverImgWidth;
            coverLeft = 0;
            coverTop = (coverImgHeight - coverBoxHeight) / 2;
          };
          context.save();
          context.beginPath()
          context.rect(0, 0, canvasWidth, coverBoxHeight);
          context.fill();
          context.clip()
          context.drawImage(cover_obj.res.path, -coverLeft, -coverTop, coverImgWidth + 2, coverImgHeight);
          context.restore();

          context.save();
          let r = 64;
          let d = r * 2;
          let cx = 20;
          let cy = coverBoxHeight - r;
          context.beginPath();
          context.setStrokeStyle("#fff");
          context.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
          context.stroke()
          context.clip();
          context.drawImage(avatar_obj.res.path, cx, cy, d, d);
          context.restore();

          context.setFontSize(21);
          context.setTextAlign('left');
          context.setTextBaseline('top');
          context.setFillStyle("#222222");
          let nickNameText = limitLength(userInfo.nickName);
          context.fillText(nickNameText, 20, coverBoxHeight + 80);
          
          if (me.data.gender){
            let nickNameWidth = context.measureText(nickNameText).width;
            context.drawImage(gender_obj.res.path, nickNameWidth + 30, coverBoxHeight + 86, 16, 16);
          }
          

          let followStr = '粉丝 ' + userInfo.userFollowedCount + ' • ' + '关注 ' + userInfo.userFolloweeCount;
          context.setFontSize(14);
          context.setTextAlign('left');
          context.setTextBaseline('top');
          context.setFillStyle("#6D7378");
          context.fillText(followStr, 20, coverBoxHeight + 112);

          context.drawImage(erweima_obj.res.path, canvasWidth - 92, coverBoxHeight+38, 72, 72);

          context.setFontSize(10);
          context.setTextAlign('right');
          context.setTextBaseline('top');
          context.setFillStyle("#525558");
          context.fillText('扫描或长按小程序码', canvasWidth - 11, coverBoxHeight+118);

          context.draw(false,()=>{
            setTimeout(function () {
              wx.canvasToTempFilePath({
                canvasId: 'myCanvas',
                fileType: 'jpg',
                success: function (res) {
                  wx.hideLoading();
                  me.setData({
                    canvasHidden: true,
                  });
                  wx.previewImage({
                    current: res.tempFilePath,
                    urls: [res.tempFilePath]
                  })
                }
              })
            }, 500);
          });

        });
      })
    })

  },
  closePop:function(e){
    setTimeout(() => {
      this.setData({
        isPopShow: false,
        popParams: {}
      },()=>{
        if (this.data.userInfo.id === LoginStore.userInfo.userId) {
          let options = this.data.options;
          getDefault();
          this.aferOnLoad(options)
        }
      })
    }, 202);
  },
  popShow: function (e) {
    let key = e.currentTarget.dataset.key;
    let count = this.data.userInfo.userFollowedCount;
    if (key === 'follow') {
      count = this.data.userInfo.userFolloweeCount;
    };
    this.setData({
      isPopShow: true,
      popParams: {
        count: count,
        popKey: key,
        curUserId: this.data.userInfo.id
      }
    });
  },
  followAction: function (e){
    let me = this;
    let userInfo = this.data.userInfo;
    let callback = ()=>{
      me.afterLoginFun(me.data.options);
    }
    let resback = ()=>{
      me.setData({
        userInfo: userInfo
      })
    }
    followAction(e, me, userInfo, "userInfo", callback,resback);
    
  },
  setTabs:function(){
    let tabEl = this.selectComponent('#worksTabs')
    if (!tabEl) {
      return
    }
    if (LoginStore.userInfo.userId === this.data.userInfo.id) {
      tabEl.setTabs([{
        displayName: '公开',
        name: 'profileList'
      }, {
        displayName: '全部',
        name: 'all'
      }, {
        displayName: '影集',
        name: 'imgAlbum'
      }], (item) => {
        this._tabclick({
          detail: {
            name: item.name
          }
        })
      })
    } else {
      tabEl.setTabs([{
        displayName: '公开',
        name: 'profileList'
      },{
        displayName: '影集',
        name: 'imgAlbum'
      }], (item) => {
        this._tabclick({
          detail: {
            name: item.name
          }
        })
      })
    }
  },
  afterLoginFun: function (options){
    console.log(options);
    let userAccountInfo = LoginStore.userInfo;
    wx.showLoading({
      title: 'loading...',
      mask:true
    });
    let me = this;
    // 15f8dbf6d417aa75823d32e6906c14051
    wx.request({
      url: `${proxy}/community/v2/user/indexInfo?queriedUserId=${options.userId}`,
      data: {
        access_token: userAccountInfo.access_token || '',
      },
      header: reqHeader,
      success: function (res) {
        res = res.data;
        if (res.status == 200) {
          let userInfo = res.data;
          let vIcon = true;
          let gender = '';
          let self = false;
          if (isNaN(parseInt(userInfo.gicCreativeId)) && isNaN(parseInt(userInfo.gicEditorialId))) {
            vIcon = false;
          };
          if (userInfo.sex && userInfo.sex === '1') {
            gender = "https://node.500px.me/images/WeChat/icon_male.png";
          } else if (userInfo.sex && userInfo.sex === '2') {
            gender = "https://node.500px.me/images/WeChat/icon_female.png";
          };
          if (userAccountInfo.userId && userAccountInfo.userId === userInfo.id) {
            self = true;
            
          };
          if (!userInfo.avatar.a1) {
            userInfo.avatar.a1 = 'https://img.500px.me/default_tx.png!a1';
          }
          me.setData({
            userInfo: userInfo,
            vIcon: vIcon,
            gender: gender,
            self: self,
            options:options,
            userReviewState: userInfo.userReviewState,
            appParams:JSON.stringify({
              category:"userDetail",
              id:userInfo.id
            }),
            totalWorksUrl: `/pages/userWorks/userWorks?userId=${userInfo.id}`,
            articleUrl: `${proxy}/community/v2/user/graphic`,
            articleParams: {
              resourceType: '3',
              imgsize: 'p1,p2,p3',
              queriedUserId: userInfo.id,
              page: 1,
              size: 2,
              type: 'json'
            },
            totalArticleUrl: `/pages/userGraphic/userGraphic?userId=${userInfo.id}`,
            communityUrl: `${proxy}/community/tribe/myTribes`,
            communityParams: {
              orderBy: 'score',
              imgsize: 'p1,p2,p3',
              queryId: userInfo.id,
              page: 1,
              size: 4,
              type: 'json'
            },
            totalCommunityUrl: `/pages/userCommunity/userCommunity?userId=${userInfo.id}`,
          }, function () {
            me.setTabs();
            wx.hideLoading();
          });
          
        } else {
          console.log(res.message);
        }    
      }
    });
  },
  aferOnLoad: function (options){
    let me = this;
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      getparamstr(scene, function (paramStr) {
        options.userId = paramStr;
        me.afterLoginFun(options);
      })

    } else {
      me.afterLoginFun(options);
    }  
  },
  onLoad: function (options) {
    this.aferOnLoad(options)
  },

  _tabclick:function(e){
    let item = e.detail;
    let userInfo = this.data.userInfo;
    let worksUrl = '';
    let worksParams = {}
    let totalWorksUrl = `/pages/userWorks/userWorks?userId=${userInfo.id}`;
    if (item.name === 'profileList') {
      worksUrl = `${proxy}/community/v2/user/profile`;
      worksParams = {
        resourceType: '0,2',
        imgsize: 'p1,p2,p3',
        queriedUserId: userInfo.id,
        page: 1,
        size: 6,
        type: 'json'
      };
      totalWorksUrl = `/pages/userWorks/userWorks?userId=${userInfo.id}&tab=profileList`;
    } else if (item.name === 'all') {
      worksUrl = `${proxy}/community/v2/user/myphoto`;
      worksParams = {
        resourceType: '0,2',
        imgsize: 'p1,p2,p3',
        page: 1,
        size: 6,
        type: 'json'
      };
      totalWorksUrl = `/pages/userWorks/userWorks?userId=${userInfo.id}&tab=all`;
    } else if (item.name === 'imgAlbum'){
      worksUrl = `${proxy}/community/user-details/${userInfo.id}/set`;
      worksParams = {
        page: 1,
        size: 6,
        type: 'json'
      };
      totalWorksUrl = `/pages/userWorks/userWorks?userId=${userInfo.id}&tab=imgAlbum`;
    }

    this.setData({
      worksUrl,
      worksParams,
      curWorksType: item.name,
      totalWorksUrl
    })
  },
  editInfo:function(){
    wx.navigateTo({
      url: '/pages/editInfo/editInfo',
    });
  },
  showChangeAccount:function(){
    let loginId = LoginStore.userInfo.userId;
    if (!loginId){
      return;
    }
    let curUserId = this.data.userInfo.id;
    if (curUserId != loginId){
      return;
    }
    
    this.setData({
      isChangeAccount:true,
      loginTypeStr: LoginStore.userInfo.loginType || ""
    })
  },
  closeAccountPop:function(){
    this.setData({
      isChangeAccount: false
    })
  },
  miniFail:function(e){
    console.log(e);
  },
  reviewHandler:function(){
    this.setData({
      userReviewState:null
    })
  },
  applyReview:function(){
    let me = this;
    wx.request({
      url: `${proxy}/community/v2/user/apply/review`,
      data: {
        access_token: LoginStore.userInfo.access_token
      },
      header: reqHeader,
      success: function (data) {
        me.reviewHandler();
      },
      fail: function (e) {
        console.log(e);
      }
    });
    maiDian('miniprogram-profilemyself-queueconfirm',function(data){
      let res = data.data;
      if(res.status == 200){
        console.log('排队审核埋点成功');
      }else{
        console.log(res.message);
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.freshMark == undefined || !this.data.freshMark) {
      return;
    }

    let options = this.data.options;

    getDefault();
    this.aferOnLoad(options)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      freshMark: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.userInfo.nickName + "的摄影圈",
      imageUrl: this.data.userInfo.coverUrl.baseUrl+'!wechat'
    }
  }
})